
// <copyright file="DataHelper.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   This static class is a helper class. It has helper methods to build DataTable and DataSet from a xml string.
// </summary>

namespace SubhadraSolutions.Sharp.Utils.Data.Helpers
{
    using System;
    using System.Data;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;

    /// <summary>
    /// This static class is a helper class. It has helper methods to build DataTable and DataSet from a xml string.
    /// </summary>
    public static class DataHelper
    {
        #region Public Methods and Operators

        /// <summary>
        /// The get value from data record.
        /// </summary>
        /// <param name="record">
        /// The record.
        /// </param>
        /// <param name="index">
        /// The index.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        public static T GetValueFromDataRecord<T>(IDataRecord record, int index)
        {
            object o = record[index];
            return o == DBNull.Value || o == null ? default(T) : (T)o;
        }

        /// <summary>
        /// Reads the data set from XML.
        /// </summary>
        /// <param name="xml">
        /// The XML.
        /// </param>
        /// <returns>
        /// The <see cref="DataSet"/>.
        /// </returns>
        public static DataSet ReadDataSetFromXml(string xml)
        {
            return ReadFromXml<DataSet>(xml);
        }

        /// <summary>
        /// Reads the data table from XML.
        /// </summary>
        /// <param name="xml">
        /// The XML.
        /// </param>
        /// <returns>
        /// DataTable.
        /// </returns>
        public static DataTable ReadDataTableFromXml(string xml)
        {
            return ReadFromXml<DataTable>(xml);
        }

        /// <summary>
        /// Reads from XML.
        /// </summary>
        /// <typeparam name="T">
        /// </typeparam>
        /// <param name="xml">
        /// The XML.
        /// </param>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        public static T ReadFromXml<T>(string xml) where T : IXmlSerializable, new()
        {
            using (var reader = new StringReader(xml))
            {
                using (var xReader = new XmlTextReader(reader))
                {
                    var obj = new T();
                    obj.ReadXml(xReader);
                    return obj;
                }
            }
        }

        #endregion Public Methods and Operators
    }
}